package com.ftg.learn.framework.sm;

import com.mysql.cj.jdbc.MysqlDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * 整合类
 *   spring 配置类
 * @Bean ： 把方法返回值 做为组件存储到容器里面
 * @author 布衣
 */
@Configuration
public class SpringMybatisConfiguration {

    /**
     * 初始化数据源
     * @return
     */
    @Bean
    public DataSource initDataSource(){
        //mysql
        MysqlDataSource d = new MysqlDataSource();
        d.setURL("jdbc:mysql://localhost:3306/dbnd");
        d.setUser("root");
        d.setPassword("123456");
        return d;
    }

    @Bean
    public Environment initEnvironment(){
        Environment env = new Environment("local",new JdbcTransactionFactory(),initDataSource());
        return env;
    }

    @Bean
    public org.apache.ibatis.session.Configuration  initConfiguration(){

        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        //日志
        configuration.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);

        //环境
        configuration.setEnvironment(this.initEnvironment());

        configuration.addMappers("com.ftg.learn.framework.sm.mapper");

        return configuration;
    }

    /**
     * 初始化sqlSessionFactory
     * @return
     */
    @Bean
    public SqlSessionFactory initSqlSessionFactory(){
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        return builder.build(this.initConfiguration());
    }

    @Bean
    public SqlSession initSqlSession(){
        return this.initSqlSessionFactory().openSession();
    }

}
